﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using RooHui.OA.Biz;
using RooHui.Infrastructure.Entities.Entity;
using RooHui.Tool;
using System.Drawing.Imaging;
using System.Drawing;
using System.IO;
using RooHui.OA.Web.Model;

namespace RooHui.Admin.Web.Controllers
{
    public class GuarCompanyController : Controller
    {
        public static string tempGuarCpyPath = "/Content/Resource/GuaCompanyTemp/";
        public static string regGuarCpyPath = "/Content/Resource/GuaCompany/";
        //
        // GET: /GuaranteeCompany/
        public ActionResult Index()
        {
            return View();
        }

        public ActionResult GetGuarCompanyListByKey(string key = "")
        {
            var guarCompanyList = GuarCompanyBiz.GetGuaranteeCompanyList(key);


            guarCompanyList.Insert(0, new GuaranteeCompany() { ID = -1, CompanyName = "全部" });

            return Content(guarCompanyList.ToJson());
        }

        /// <summary>
        /// 获取启用的担保公司
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ActionResult GetEnabledGuarCompany()
        {
            var guarCompanyList = GuarCompanyBiz.GetGuaranteeCompanyByStatus(1);
            guarCompanyList.Insert(0, new GuaranteeCompany() { ID = -1, CompanyName = "请选择", LogoImage = "" });

            return Content(guarCompanyList.ToJson());
        }

        /// <summary>
        /// 分页获取担保公司信息
        /// </summary>
        /// <param name="page"></param>
        /// <param name="pageSize"></param>
        /// <returns></returns>
        [HttpPost]
        public ActionResult GetGuarCompanyListByPage(int page, int pageSize, string key = "")
        {
            int count = 0;
            var getGuarCompanyList = GuarCompanyBiz.GetGuarCompanyListByPage(page, pageSize, key, ref count);
            Dictionary<string, object> dic = new Dictionary<string, object>();
            dic.Add("Rows", getGuarCompanyList);
            dic.Add("Total", count);
            return Content(dic.ToJson());
        }

        public ActionResult GuarCompanyAdd()
        {
            return View();
        }

        /// <summary>
        /// 获取担保公司详情
        /// </summary>
        /// <param name="guarCompanyId"></param>
        /// <param name="editType"></param>
        /// <returns></returns>
        public ActionResult GuarCompanyEdit(int guarCompanyId, int editType)
        {
            ViewBag.guarcompany = GuarCompanyBiz.GetGuarCompanyByID(guarCompanyId);
            ViewBag.editType = editType;
            return View();
        }

        /// <summary>
        /// 增加/修改担保公司
        /// </summary>
        /// <param name="editType"></param>
        /// <param name="guarCompanyId"></param>
        /// <param name="companyName"></param>
        /// <param name="logoImage"></param>
        /// <param name="summary"></param>
        /// <param name="description"></param>
        /// <param name="qualificationsImages"></param>
        /// <param name="agreementImages"></param>
        /// <returns></returns>
        [HttpPost]
        public ActionResult GuarCompanySave(int editType, int guarCompanyId, string companyName, string logoImage, string summary, string description, string qualificationsImages, string agreementImages)
        {
            bool bSaveFlag = false;
            logoImage = regGuarCpyPath + logoImage;
            qualificationsImages = regGuarCpyPath + qualificationsImages;
            agreementImages = regGuarCpyPath + agreementImages;
            if (editType == 1)
            {
                bSaveFlag = GuarCompanyBiz.GuarCompanyAdd(companyName, logoImage, summary, description, qualificationsImages, agreementImages);
            }
            else if (editType == 2)
            {
                bSaveFlag = GuarCompanyBiz.GuarCompanyEdit(guarCompanyId, companyName, logoImage, summary, description, qualificationsImages, agreementImages);
            }
            if (bSaveFlag)
            {
                MoveTempFile(companyName);
            }
            filelist = new List<SWFUploadItem>(); // 清空
            return Content(bSaveFlag.ToString());
        }

        /// <summary>
        /// 删除担保公司信息
        /// </summary>
        /// <param name="id"></param>
        /// <param name="page"></param>
        /// <returns></returns>
        [HttpPost]
        public ActionResult GuarCompanyStatusChange(int guarCompanyId, int destinatStatus)
        {
            bool bChangeFlag = GuarCompanyBiz.GuarCompanyStatusChange(guarCompanyId, destinatStatus);
            return Content(bChangeFlag.ToString());
        }

        public static List<SWFUploadItem> filelist = new List<SWFUploadItem>();

        public void SWFPrepareUpload()
        {
            try
            {
                if (!System.IO.Directory.Exists(Server.MapPath(tempGuarCpyPath)))
                {
                    System.IO.Directory.CreateDirectory(Server.MapPath(tempGuarCpyPath));
                }
                var file = Request.Files["Filedata"];
                //string fileName = file.FileName.Remove(file.FileName.LastIndexOf('.')) + "_" + DateTime.Now.ToString("yyMMddhhssmm") + file.FileName.Substring(file.FileName.LastIndexOf('.'));
                string filePath = tempGuarCpyPath + file.FileName;
                bool isHorizontal = SaveAndZoom(file, Server.MapPath(tempGuarCpyPath + file.FileName));
                filelist.Add(new SWFUploadItem() { path = filePath, name = file.FileName, horizontal = isHorizontal.ToString() });
                Response.Write("{oldname:'" + file.FileName.Remove(file.FileName.LastIndexOf('.')) + "','name':'" + file.FileName + "','path':'" + filePath + "','horizontal':'" + isHorizontal + "'}");
            }
            catch (Exception e)
            {
                Response.StatusCode = 500;
                Response.Write("");
            }
        }

        /// <summary>
        /// 上传
        /// </summary>
        /// <param name="msg"></param>
        /// <param name="imgs"></param>
        public void SWFUpload(string msg, string imgs)
        {
            Response.Write(filelist.ToJson());
        }

        /// <summary>
        /// 移动临时文件
        /// </summary>
        public void MoveTempFile(string guacpyname)
        {
            foreach (var item in filelist)
            {
                if (item != null)
                {
                    string newfilename = item.path.Replace(tempGuarCpyPath, regGuarCpyPath);
                    if (!System.IO.Directory.Exists(Server.MapPath(regGuarCpyPath)))
                    {
                        System.IO.Directory.CreateDirectory(Server.MapPath(regGuarCpyPath));
                    }
                    System.IO.File.Copy(Server.MapPath(item.path), Server.MapPath(newfilename), true);
                    System.IO.File.Delete(Server.MapPath(item.path));
                }
            }
            if (System.IO.Directory.Exists(Server.MapPath(tempGuarCpyPath)))
            {
                System.IO.Directory.Delete(Server.MapPath(tempGuarCpyPath), true);
            }
        }

        /// <summary>  
        /// 图片等比缩放
        /// </summary>   
        /// <param name="postedFile">原图HttpPostedFile对象</param>  
        /// <param name="savePath">缩略图存放地址</param>  
        public static bool SaveAndZoom(System.Web.HttpPostedFileBase postedFile, string savePath)
        {
            bool isHorizontal = true;
            //创建目录  
            string dir = Path.GetDirectoryName(savePath);
            if (!Directory.Exists(dir))
            {
                Directory.CreateDirectory(dir);
            }
            //原始图片（获取原始图片创建对象，并使用流中嵌入的颜色管理信息）  
            System.Drawing.Image initImage = System.Drawing.Image.FromStream(postedFile.InputStream, true);

            double zoomHeight = 600;
            double zoomWidth = 800;
            if (initImage.Width < initImage.Height)
            {
                //如果是平的。要求save width:1024 height:768; 
                //否则 width:768 height: 1024
                zoomHeight = 800;
                zoomWidth = 600;
                isHorizontal = false;
            }

            //缩略图宽、高计算  
            double newWidth = initImage.Width;
            double newHeight = initImage.Height;
            //宽大于高或宽等于高（横图或正方）  
            if (initImage.Width > initImage.Height || initImage.Width == initImage.Height)
            {
                //如果宽大于模版  
                if (initImage.Width > zoomWidth)
                {
                    //宽按模版，高按比例缩放  
                    newWidth = zoomWidth;
                    newHeight = initImage.Height * (zoomWidth / initImage.Width);
                }
            }
            //高大于宽（竖图）  
            else
            {
                //如果高大于模版  
                if (initImage.Height > zoomHeight)
                {
                    //高按模版，宽按比例缩放  
                    newHeight = zoomHeight;
                    newWidth = initImage.Width * (zoomHeight / initImage.Height);
                }
            }
            //生成新图  
            //新建一个bmp图片  
            System.Drawing.Image newImage = new System.Drawing.Bitmap((int)newWidth, (int)newHeight);
            //新建一个画板  
            System.Drawing.Graphics newG = System.Drawing.Graphics.FromImage(newImage);
            //设置质量  
            newG.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.HighQualityBicubic;
            newG.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality;

            //置背景色  
            newG.Clear(Color.White);
            //画图  
            newG.DrawImage(initImage, new System.Drawing.Rectangle(0, 0, newImage.Width, newImage.Height), new System.Drawing.Rectangle(0, 0, initImage.Width, initImage.Height), System.Drawing.GraphicsUnit.Pixel);

            //保存缩略图                  
            newImage.Save(savePath, System.Drawing.Imaging.ImageFormat.Jpeg);

            //释放资源  
            newG.Dispose();
            newImage.Dispose();
            initImage.Dispose();
            return isHorizontal;
        }

    }
}